package com.atguigu.demo.filter;

import com.alibaba.fastjson.JSON;
import com.atguigu.demo.entity.Result;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;

import java.io.IOException;

@WebFilter(filterName = "ResultFilter", urlPatterns = "/*")
public class ResultFilter extends HttpFilter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            Result<Void> result = Result.failed(55555, e.getMessage());
            String jsonString = JSON.toJSONString(result);

            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(jsonString);
        }
    }
}
